#include <list>
#include <iostream>

using namespace std;

int LastRemaining_Solution(int n, int m)
{
	if (n < 1 || m < 1) return -1;
	list<int> cycle;
	for (int i = 0; i < n; ++i)
		cycle.push_back(i);
	list<int>::iterator listIt = cycle.begin();
	while (cycle.size() > 1)
	{
		for (int j = 1; j < m; ++j)
		{
			++listIt;
			if (listIt == cycle.end())
				listIt = cycle.begin();
		}
		listIt = cycle.erase(listIt);
		if (listIt == cycle.end())
			listIt = cycle.begin();
	}
	return *listIt;
}


//int main()
//{
//	cout << LastRemaining_Solution(5, 2);
//
//	system("pause");
//	return 0;
//}